/*
 * Copyright (C) 2008, 2009 The Android Open source Project
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *  * Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *  * Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
 * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 */

/*
 * Symbol search order is:
 *   Main Executable
 *   Breadth first search of DT_NEEDED
 */


#include <dlfcn.h>
#include <errno.h>
#include <fcntl.h>
#include <linux/auxvec.h>
#include <pthread.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/atomics.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <unistd.h>

// Private C library headers.
#include <private/bionic_tls.h>
#include <private/logd.h>

// NACL MOD BEGIN
// Add includes.
#if defined(__native_client__)
#include <irt_syscalls.h>
#include "arch/nacl/nacl_dyncode.h"
#include <private/dl_dst_lib.h>
#endif
// NACL MOD END
#include "debug_map.h"
#include "linker.h"
#include "linker_debug.h"
#include "linker_environ.h"
#include "linker_format.h"
#include "linker_phdr.h"

#define ALLOW_SYMBOLS_FROM_MAIN 1
#define SO_MAX 128

#define LDPATH_BUFSIZE 512
#define LDPATH_MAX 8

#define LDPRELOAD_BUFSIZE 512
#define LDPRELOAD_MAX 8

//#define EXTERN_C extern "C"
#define EXTERN_C

extern struct r_debug _r_debug;

static int socount = 0;
static soinfo sopool[SO_MAX];

static soinfo *freelist = NULL;

static soinfo *solist = &libdl_info;
static soinfo *somain;


static char ldpaths_buf[LDPATH_BUFSIZE];
static const char *ldpaths[LDPATH_MAX + 1];

#if LINKER_DEBUG
int debug_verbosity = 0;
#endif

static int pid;

/* This boolean is set if the program being loaded is setuid */
static bool program_is_setuid;

#define count_relocation(x)
#define MARK(x)

// You shouldn't try to call memory-allocating functions in the dynamic linker.
// Guard against the most obvious ones.
#define DISALLOW_ALLOCATION(return_type, name, ...)                             \
    return_type name __VA_ARGS__                                                \
    {                                                                           \
        const char* msg = "ERROR: " #name " called from the dynamic linker!\n"; \
         __libc_android_log_write(ANDROID_LOG_FATAL, "linker", msg);            \
        write(2, msg, sizeof(msg));                                             \
        abort();                                                                \
    }
#define UNUSED __attribute__((unused))
DISALLOW_ALLOCATION(void*, malloc, (size_t u UNUSED));
DISALLOW_ALLOCATION(void, free, (void* u UNUSED));
DISALLOW_ALLOCATION(void*, realloc, (void* u1 UNUSED, size_t u2 UNUSED));
DISALLOW_ALLOCATION(void*, calloc, (size_t u1 UNUSED, size_t u2 UNUSED));

static char tmp_err_buf[768];
static char __linker_dl_err_buf[768];

#define BASENAME(s) (strrchr(s, '/') != NULL ? strrchr(s, '/') + 1 : s)
#define DL_ERR(fmt, x...) \
    do { \
        format_buffer(__linker_dl_err_buf, sizeof(__linker_dl_err_buf), \
                      "%s(%s:%d): " fmt, \
                      __FUNCTION__, BASENAME(__FILE__), __LINE__, ##x); \
        ERROR(fmt "\n", ##x); \
    } while(0)

const char *linker_get_error(void)
{
    return (const char *)&__linker_dl_err_buf[0];
}


static soinfo *soinfo_alloc(const char *name)
{
    if (strlen(name) >= SOINFO_NAME_LEN) {
        DL_ERR("library name \"%s\" too long", name);
        return NULL;
    }

    /* The freelist is populated when we call soinfo_free(), which in turn is
       done only by dlclose(), which is not likely to be used.
    */
    if (!freelist) {
        if (socount == SO_MAX) {
            DL_ERR("too many libraries when loading \"%s\"", name);
            return NULL;
        }
        freelist = sopool + socount++;
        freelist->next = NULL;
    }

    soinfo* si = freelist;
    freelist = freelist->next;

    /* Make sure we get a clean block of soinfo */
    memset(si, 0, sizeof(soinfo));
    strlcpy((char*) si->name, name, sizeof(si->name));
    si->next = NULL;
    si->refcount = 0;

    DEBUG(3, "%s allocated soinfo @ %p\n", name, si);
    return si;
}

static void soinfo_free(soinfo* si)
{
    if (si == NULL) {
        return;
    }

    soinfo *prev = NULL, *trav;

    DEBUG(3, "%s freeing soinfo @ %p\n", si->name, si);

    for(trav = solist; trav != NULL; trav = trav->next){
        if (trav == si)
            break;
        prev = trav;
    }
    if (trav == NULL) {
        /* si was not ni solist */
        DL_ERR("name \"%s\" is not in solist!", si->name);
        return;
    }

    /* prev will never be NULL, because the first entry in solist is
       always the static libdl_info.
    */
    prev->next = si->next;
    si->next = freelist;
    freelist = si;
}

static int soinfo_chain(soinfo* si) {
    // Find parent of lsi and unlink lsi 
    soinfo* me_prev = solist;
    if (NULL == solist) {
      DEBUG(1, "  SOLIST broken, sould have a parent.\n");
      return 1;
    }
 
    while (me_prev->next && me_prev->next->depth <= si->depth)
      me_prev = me_prev->next;

    DEBUG(2, " Inserting %s (%d) after %s (%d).\n",
          si->name, si->depth, me_prev->name, me_prev->depth);

   si->next = me_prev->next;
   me_prev->next = si;
   return 0;
}

#ifdef ANDROID_ARM_LINKER

/* For a given PC, find the .so that it belongs to.
 * Returns the base address of the .ARM.exidx section
 * for that .so, and the number of 8-byte entries
 * in that section (via *pcount).
 *
 * Intended to be called by libc's __gnu_Unwind_Find_exidx().
 *
 * This function is exposed via dlfcn.c and libdl.so.
 */
_Unwind_Ptr dl_unwind_find_exidx(_Unwind_Ptr pc, int *pcount)
{
    soinfo *si;
    unsigned addr = (unsigned)pc;

    for (si = solist; si != 0; si = si->next){
        if ((addr >= si->base) && (addr < (si->base + si->size))) {
            *pcount = si->ARM_exidx_count;
            return (_Unwind_Ptr)si->ARM_exidx;
        }
    }
   *pcount = 0;
    return NULL;
}

// NACL MOD BEGIN
#endif
// Add dl_iterate_phdr for x86-64 and arm.
#if defined(ANDROID_X86_LINKER) || defined(ANDROID_MIPS_LINKER) \
    || defined(ANDROID_X86_64_LINKER) || defined(ANDROID_ARM_LINKER)
// NACL MOD END

/* Here, we only have to provide a callback to iterate across all the
 * loaded libraries. gcc_eh does the rest. */
int
dl_iterate_phdr(int (*cb)(struct dl_phdr_info *info, size_t size, void *data),
                void *data)
{
    int rv = 0;
    for (soinfo* si = solist; si != NULL; si = si->next) {
        struct dl_phdr_info dl_info;
        dl_info.dlpi_addr = si->linkmap.l_addr;
        dl_info.dlpi_name = si->linkmap.l_name;
        dl_info.dlpi_phdr = si->phdr;
        dl_info.dlpi_phnum = si->phnum;
        rv = cb(&dl_info, sizeof(struct dl_phdr_info), data);
        if (rv != 0) {
            break;
        }
    }
    return rv;
}

#endif

static Elf32_Sym *soinfo_elf_lookup(soinfo *si, unsigned hash, const char *name)
{
    Elf32_Sym *s;
    Elf32_Sym *symtab = si->symtab;
    const char *strtab = si->strtab;
    unsigned n;

    DEBUG(4, "SEARCH %s in %s@0x%08x\n",
             name, si->name, si->base);
    n = hash % si->nbucket;

    for(n = si->bucket[hash % si->nbucket]; n != 0; n = si->chain[n]){
        s = symtab + n;
        if(strcmp(strtab + s->st_name, name)) continue;

            /* only concern ourselves with global and weak symbol definitions */
        // NACL MOD BEGIN
        // Use ELFW(ST_BIND) instead of ELF32_ST_BIND.
        switch (ELFW(ST_BIND)(s->st_info)) {
        // NACL MOD END
        case STB_GLOBAL:
        case STB_WEAK:
            if(s->st_shndx == SHN_UNDEF)
                continue;

            DEBUG(4, "FOUND %s in %s (%08x) %d\n",
                  name, si->name, s->st_value, s->st_size);
            return s;
        }
    }

    return NULL;
}

static unsigned elfhash(const char *_name)
{
    const unsigned char *name = (const unsigned char *) _name;
    unsigned h = 0, g;

    while(*name) {
        h = (h << 4) + *name++;
        g = h & 0xf0000000;
        h ^= g;
        h ^= g >> 24;
    }
    return h;
}

static Elf32_Sym *soinfo_do_lookup(soinfo* self, const char *name,
                                   Elf32_Addr *offset, bool ignore_local) {

  unsigned elf_hash = elfhash(name);
  Elf32_Sym *s = NULL;

  /* Search always begins libdl followed by the the main process. */
  soinfo* si = solist;

  while (si) {
    if ((si != self) || (ignore_local == 0)) {
      s = soinfo_elf_lookup(si, elf_hash, name);
      if(s != NULL) {
        DEBUG(2, "%s FOUND %s s->st_value = 0x%08x in %s\n",
              //"found in %s, base = 0x%08x, load bias = 0x%08x\n",
              self->name, name, s->st_value, si->name);
              // si->name, si->base, si->load_bias);
        *offset = si->load_bias;
        return s;
      }
    } else {
      DEBUG(2, "%s IGNORE SELF for %s.\n", self->name, name);
    }
    DEBUG(3, "%s could not find %s in %s.\n", self->name, name, si->name);
    si = si->next;
  }

  DEBUG(4, "%s COULD NOT FIND %s.\n", self->name, name);
  return NULL;
}


/*
 * This is used by dl_sym().  It performs symbol lookup only within the
 * specified soinfo object and not in any of its dependencies.
 */
Elf32_Sym *soinfo_lookup(soinfo *si, const char *name)
{
    return soinfo_elf_lookup(si, elfhash(name), name);
}

/*
 * This is used by dl_sym().  It performs a global symbol lookup.
 */
Elf32_Sym *lookup(const char *name, soinfo **found, soinfo *start)
{
    unsigned elf_hash = elfhash(name);
    Elf32_Sym *s = NULL;
    soinfo *si;

    *found = NULL;
    if(start == NULL) {
        start = solist;
    }

    for(si = start; (s == NULL) && (si != NULL); si = si->next)
    {
        if(si->flags & FLAG_ERROR)
            continue;
        s = soinfo_elf_lookup(si, elf_hash, name);
        if (s != NULL) {
            *found = si;
            break;
        }
    }

    return s;
}

soinfo *find_containing_library(const void *addr)
{
    soinfo *si;

    for(si = solist; si != NULL; si = si->next)
    {
        if((unsigned)addr >= si->base && (unsigned)addr - si->base < si->size) {
            return si;
        }
    }

    return NULL;
}

Elf32_Sym *soinfo_find_symbol(soinfo* si, const void *addr)
{
    unsigned int i;
    // NACL MOD BEGIN UPSTREAM
    // Use si->load_bias instead of si->base. This si->base works for
    // shared objects but does not work for the main binary. The load
    // bias of a main binary is not as same as si->base of the main
    // binary unless the binary is a PIE. For example, si->load_bias
    // of a NaCl main binary is 0 but its base is 0x10000.
    unsigned soaddr = (unsigned)addr - si->load_bias;
    // NACL MOD END UPSTREAM

    /* Search the library's symbol table for any defined symbol which
     * contains this address */
    for(i=0; i<si->nchain; i++) {
        Elf32_Sym *sym = &si->symtab[i];

        if(sym->st_shndx != SHN_UNDEF &&
           soaddr >= sym->st_value &&
           soaddr < sym->st_value + sym->st_size) {
            return sym;
        }
    }

    return NULL;
}


extern int nacl_irt_open_resource(const char *, int*);
static int _open_lib(const char* name) {
  int fd;
  int err = 0;

  if (__nacl_irt_open_resource) {
    err = __nacl_irt_open_resource(name, &fd);
  } else {
    fd = open(name, O_RDONLY);
    if (fd < 0)
      err = errno;
  }
  if (err != 0)
    return -1;

  return fd;
}

static int open_library(const char *name)
{
    int fd;
    char buf[512];
    const char * const*path;
    int n;

    if(name == 0) return -1;
    if(strlen(name) > 256) return -1;

    if ((fd = _open_lib(name)) >= 0)
      return fd;

    for (path = ldpaths; *path; path++) {
        n = format_buffer(buf, sizeof(buf), "%s/%s", *path, name);
        if (n < 0 || n >= (int)sizeof(buf)) {
            DEBUG(0, "Ignoring very long library path: %s/%s\n", *path, name);
            continue;
        }
        if ((fd = _open_lib(buf)) >= 0)
            return fd;
    }
    return -1;
}

// Returns 'true' if the library is prelinked or on failure so we error out
// either way. We no longer support prelinking.
static bool is_prelinked(int fd, const char* name)
{
    struct prelink_info_t {
        long mmap_addr;
        char tag[4]; // "PRE ".
    };

    off_t sz = lseek(fd, 0 - ((off_t) sizeof(struct prelink_info_t)), SEEK_END);
    if (sz < 0) {
        DL_ERR("lseek failed: %s", strerror(errno));
        return true;
    }

    struct prelink_info_t info;
    int rc = TEMP_FAILURE_RETRY(read(fd, &info, sizeof(info)));
    if (rc != sizeof(info)) {
        DL_ERR("could not read prelink_info_t structure for \"%s\":", name, strerror(errno));
        return true;
    }

    if (memcmp(info.tag, "PRE ", 4) == 0) {
        DL_ERR("prelinked libraries no longer supported: %s", name);
        return true;
    }
    return false;
}

/* verify_elf_header
 *      Verifies the content of an ELF header.
 *
 * Args:
 *
 * Returns:
 *       0 on success
 *      -1 if no valid ELF object is found @ base.
 */
static int
verify_elf_header(const Elf32_Ehdr* hdr)
{
    if (hdr->e_ident[EI_MAG0] != ELFMAG0) return -1;
    if (hdr->e_ident[EI_MAG1] != ELFMAG1) return -1;
    if (hdr->e_ident[EI_MAG2] != ELFMAG2) return -1;
    if (hdr->e_ident[EI_MAG3] != ELFMAG3) return -1;
    // NACL MOD BEGIN
    // In normal linux system, kernel maps the main executable before
    // it runs a loader. On NaCl, sel_ldr does not map the main
    // executable and the loader should map the main executable.
#if defined(__native_client__)
    if (hdr->e_type != ET_EXEC)
#endif
    // NACL MOD END
    if (hdr->e_type != ET_DYN) return -1;

    /* TODO: Should we verify anything else in the header? */
#ifdef ANDROID_ARM_LINKER
    if (hdr->e_machine != EM_ARM) return -1;
#elif defined(ANDROID_X86_LINKER)
    if (hdr->e_machine != EM_386) return -1;
#elif defined(ANDROID_MIPS_LINKER)
    if (hdr->e_machine != EM_MIPS) return -1;
    // NACL MOD BEGIN
    // Add the case for x86-64.
#elif defined(ANDROID_X86_64_LINKER)
    if (hdr->e_machine != EM_X86_64) return -1;
    // NACL MOD END
#endif
    return 0;
}

// TODO: rewrite linker_phdr.h to use a class, then lose this.
struct phdr_ptr {
    void* phdr_mmap;
    Elf32_Addr phdr_size;
};

soinfo* load_library_fd_phdr(int fd, void** phdr_mmap, Elf32_Addr* phdr_size,
                             const char* name, int depth) {
    // Read the ELF header.
    Elf32_Ehdr header[1];
    int ret = TEMP_FAILURE_RETRY(read(fd, (void*)header, sizeof(header)));
    if (ret < 0) {
        DL_ERR("can't read file \"%s\": %s", name, strerror(errno));
        return NULL;
    }
    if (ret != (int)sizeof(header)) {
        DL_ERR("too small to be an ELF executable: %s", name);
        return NULL;
    }
    if (verify_elf_header(header) < 0) {
        DL_ERR("not a valid ELF executable: %s", name);
        return NULL;
    }

    // Read the program header table.
    const Elf32_Phdr* phdr_table;
    ret = phdr_table_load(fd, header->e_phoff, header->e_phnum,
                          phdr_mmap, phdr_size, &phdr_table);
    if (ret < 0) {
        DL_ERR("can't load program header table: %s: %s", name, strerror(errno));
        return NULL;
    }
    size_t phdr_count = header->e_phnum;

    // Get the load extents.
    Elf32_Addr ext_sz = phdr_table_get_load_size(phdr_table, phdr_count);
    DEBUG(3, "%s wants sz=0x%08x\n", name, ext_sz);
    if (ext_sz == 0) {
        DL_ERR("no loadable segments in file: %s", name);
        return NULL;
    }

    // We no longer support pre-linked libraries.
    if (is_prelinked(fd, name)) {
        return NULL;
    }

    // Reserve address space for all loadable segments.
    void* load_start = NULL;
    Elf32_Addr load_size = 0;
    Elf32_Addr load_bias = 0;
    ret = phdr_table_reserve_memory(phdr_table,
                                    phdr_count,
                                    &load_start,
                                    &load_size,
                                    &load_bias);
    if (ret < 0) {
        DL_ERR("can't reserve %d bytes in address space for \"%s\": %s",
               ext_sz, name, strerror(errno));
        return NULL;
    }

    DEBUG(3, "Allocated memory for %s @ %p (0x%08x)\n",
          name, load_start, load_size);

    /* Map all the segments in our address space with default protections */
    ret = phdr_table_load_segments(phdr_table, phdr_count, load_bias, fd);
    if (ret < 0) {
        DL_ERR("can't map loadable segments for \"%s\": %s",
               name, strerror(errno));
        return NULL;
    }

    size_t code_size = 0;
    for (size_t i = 0; i < phdr_count; i++) {
        if ((phdr_table[i].p_type == PT_LOAD) &&
            (phdr_table[i].p_flags & PF_X)) {
            code_size = phdr_table[i].p_memsz;
            break;
        }
    }

    DEBUG(0, "Loaded text: %p-%p %s\n",
          load_start, ((char*)load_start) + code_size, name);

    const char* bname = strchr(name, '/');
    soinfo* si = soinfo_alloc(bname ? bname + 1 : name);
    if (si == NULL) {
        DL_ERR("Failed to allocate SOINFO.\n");
        return NULL;
    }

    si->depth = depth;
    si->base = (Elf32_Addr) load_start;
    si->size = load_size;
    si->load_bias = load_bias;
    si->flags = 0;
    si->entry = 0;
    // NACL MOD BEGIN
    // dynamic changed to Elf32_Addr
    si->dynamic = (Elf32_Addr *)-1;
    // NACL MOD END
    si->phnum = phdr_count;
    si->phdr = phdr_table_get_loaded_phdr(phdr_table, phdr_count, load_bias);
    // NACL MOD BEGIN
    // Two modifications for NaCl to mitigate the difference between
    // linux and NaCl.
#if defined(__native_client__)
    // Linux kernel sends the entry point using AT_ENTRY, but sel_ldr
    // does not send this info. So, we fill this field in this chance.
    if (header->e_type == ET_EXEC) {
        si->entry = header->e_entry;
        si->flags |= FLAG_EXE;
    }
    // NaCl binary does not have PT_PHDR in the program header.
    if (si->phdr == NULL) {
        if (header->e_phoff + header->e_phentsize * header->e_phnum >
            PAGE_SIZE) {

            DL_ERR("Program header does not fit in a single page.");
            soinfo_free(si);
            return NULL;
        }
        // Take over the mmaped program header.
        // TODO(crbug.com/257546): Unmap this region when we implement dlclose.
        si->phdr = (const Elf32_Phdr *)(
            (char *) (*phdr_mmap) + header->e_phoff);
        *phdr_mmap = NULL;
    }
#endif
    // NACL MOD END
    if (si->phdr == NULL) {
        DL_ERR("can't find loaded PHDR for \"%s\"", name);
        soinfo_free(si);
        return NULL;
    }

    /* "base" might wrap around UINT32_MAX. */
    const Elf32_Phdr *phdr = si->phdr;
    int phnum = si->phnum;
    size_t dynamic_count;

    /* Extract dynamic section */
    phdr_table_get_dynamic_section(phdr, phnum, load_bias, &si->dynamic,
                                   &dynamic_count);
    if (si->dynamic == NULL) {
      DL_ERR("missing PT_DYNAMIC?!");
      soinfo_free(si);
      return NULL;
    }

    return si;
}

soinfo* load_library_process_dynamic(soinfo* si) {
#if defined(ANDROID_X86_64_LINKER)
    static const size_t rel_size = sizeof(Elf64_Rela);
#else
    static const size_t rel_size = sizeof(Elf32_Rel);
#endif

    Elf32_Addr base = si->load_bias;
    for(Elf32_Addr* d = si->dynamic; *d; d++){
      switch(*d++){
        case DT_HASH:
            si->nbucket = ((unsigned *) (base + *d))[0];
            si->nchain = ((unsigned *) (base + *d))[1];
            si->bucket = (unsigned *) (base + *d + 8);
            si->chain = (unsigned *) (base + *d + 8 + si->nbucket * 4);
            break;
        case DT_STRTAB:
            si->strtab = (const char *) (base + *d);
            break;
        case DT_SYMTAB:
            si->symtab = (Elf32_Sym *) (base + *d);
            break;
        case DT_PLTREL:
            // NACL MOD BEGIN
            // AMD64 ABI says we should always use Elf64_Rela for x86-64.
    #if defined(ANDROID_X86_64_LINKER)
            if(*d != DT_RELA) {
                DL_ERR("DT_REL not supported on 64bit");
                goto fail;
            }
    #else
            if(*d != DT_REL) {
                DL_ERR("DT_RELA not supported on 32bit");
                soinfo_free(si);
                return NULL;
            }
    #endif
            // NACL MOD END
            break;
        case DT_JMPREL:
            // NACL MOD BEGIN
            // AMD64 ABI says we should always use Elf64_Rela for x86-64.
    #if defined(ANDROID_X86_64_LINKER)
            si->plt_rel = (Elf64_Rela*) (base + *d);
    #else
            si->plt_rel = (Elf32_Rel*) (base + *d);
    #endif
            // NACL MOD END
            break;
        case DT_PLTRELSZ:
            // NACL MOD BEGIN
            // Use rel_size instead of the magic number 8.
            si->plt_rel_count = *d / rel_size;
            // NACL MOD END
            break;
        case DT_REL:
            // NACL MOD BEGIN
            // We expect Elf32_Rel (not Elf32_Rela) on 32bit CPU.
    #if defined(__x86_64__)
            DL_ERR("DT_REL not supported on 64bit");
            goto fail;
    #else
            si->rel = (Elf32_Rel*) (base + *d);
            break;
    #endif
            // NACL MOD END
        case DT_RELSZ:
            // NACL MOD BEGIN
            // We use RELASZ instead of RELSZ on x86-64.
    #if defined(ANDROID_X86_64_LINKER)
        case DT_RELASZ:
    #endif
            // NACL MOD END
            // NACL MOD BEGIN
            // Use rel_size instead of the magic number 8.
            si->rel_count = *d / rel_size;
            // NACL MOD END
            break;
        case DT_PLTGOT:
            /* Save this in case we decide to do lazy binding. We don't yet. */
            si->plt_got = (unsigned *)(base + *d);
            break;
        case DT_DEBUG:
    #if !defined(ANDROID_MIPS_LINKER)
            // Set the DT_DEBUG entry to the address of _r_debug for GDB
            *d = (int) &_r_debug;
    #endif
            break;
          case DT_RELA:
            // NACL MOD BEGIN
    #if defined(ANDROID_X86_64_LINKER)
            si->rel = (Elf64_Rela*) (base + *d);
            break;
    #else
            DL_ERR("DT_RELA not supported on 32bit");
            soinfo_free(si);
            return NULL;
    #endif
            // NACL MOD END
        case DT_INIT:
            si->init_func = (void (*)(void))(base + *d);
            DEBUG(3, "%s constructors (init func) found at %p\n",
                  si->name, si->init_func);
            break;
        case DT_FINI:
            si->fini_func = (void (*)(void))(base + *d);
            DEBUG(3, "%s destructors (fini func) found at %p\n",
                  si->name, si->fini_func);
            break;
        case DT_INIT_ARRAY:
            si->init_array = (unsigned *)(base + *d);
            DEBUG(3, "%s constructors (init_array) found at %p\n",
                  si->name, si->init_array);
            break;
        case DT_INIT_ARRAYSZ:
            si->init_array_count = ((unsigned)*d) / sizeof(Elf32_Addr);
            break;
        case DT_FINI_ARRAY:
            si->fini_array = (unsigned *)(base + *d);
            DEBUG(3, "%s destructors (fini_array) found at %p\n",
                  si->name, si->fini_array);
            break;
        case DT_FINI_ARRAYSZ:
            si->fini_array_count = ((unsigned)*d) / sizeof(Elf32_Addr);
            break;
        case DT_PREINIT_ARRAY:
            si->preinit_array = (unsigned *)(base + *d);
            DEBUG(3, "%s constructors (preinit_array) found at %p\n",
                  si->name, si->preinit_array);
            break;
        case DT_PREINIT_ARRAYSZ:
            si->preinit_array_count = ((unsigned)*d) / sizeof(Elf32_Addr);
            break;
        case DT_TEXTREL:
            si->has_text_relocations = true;
            DEBUG(3, "%s has text relocation.\n", si->name);
            break;
    #if defined(ANDROID_MIPS_LINKER)
        case DT_NEEDED:
        case DT_STRSZ:
        case DT_SYMENT:
        case DT_RELENT:
              break;
        case DT_MIPS_RLD_MAP:
            // Set the DT_MIPS_RLD_MAP entry to the address of _r_debug for GDB.
            {
              r_debug** dp = (r_debug**) *d;
              *dp = &_r_debug;
            }
            break;
        case DT_MIPS_RLD_VERSION:
        case DT_MIPS_FLAGS:
        case DT_MIPS_BASE_ADDRESS:
        case DT_MIPS_UNREFEXTNO:
        case DT_MIPS_RWPLT:
            break;

        case DT_MIPS_PLTGOT:
    #if 0
            /* not yet... */
            si->mips_pltgot = (unsigned *)(si->base + *d);
    #endif
            break;

        case DT_MIPS_SYMTABNO:
            si->mips_symtabno = *d;
            break;

        case DT_MIPS_LOCAL_GOTNO:
            si->mips_local_gotno = *d;
            break;

        case DT_MIPS_GOTSYM:
            si->mips_gotsym = *d;
            break;

        default:
            DEBUG(2, "%s has unused DT entry: type 0x%08x arg 0x%08x\n",
                  si->name, d[-1], d[0]);
            break;
    #endif
      }
    }
    DEBUG(3, "%s DYNAMIC INFO si->base = 0x%08x, si->strtab = %p, si->symtab = %p\n",
           si->name, si->base, si->strtab, si->symtab);

    if((si->strtab == 0) || (si->symtab == 0)) {
        DL_ERR("missing essential tables");
        soinfo_free(si);
        return NULL;
    }

    for (Elf32_Addr* d = si->dynamic; *d; d += 2) {
      if(d[0] == DT_NEEDED) {
        const char* need_name = si->strtab + d[1];
        soinfo *lsi = find_loaded_library(need_name);
        if (lsi) {
          if (lsi->depth <= si->depth + 1) {
            DEBUG(3, "  DT_NEEDED %s already loaded at higher priority %d.\n",
                  need_name, lsi->depth);
          } else {
            DEBUG(3, "  DT_NEEDED %s updating priority from %d to %d.\n",
                  need_name, lsi->depth, si->depth + 1);

            // Find parent of lsi and unlink lsi
            soinfo* me_prev = solist;
            while (me_prev && me_prev->next != lsi) me_prev = me_prev->next;

            if (NULL == me_prev) {
              DEBUG(1, "  Could not find parent of %s.\n", need_name);
            }
            me_prev->next = lsi->next;
            DEBUG(4, "  UNLINKING %s from %s.\n", need_name, me_prev->name);

            // Find lsi's new parent
            soinfo* prev = solist;
            while (prev->next && prev->next->depth <= si->depth + 1) prev = prev->next;
            lsi->next = prev->next;
            prev->next = lsi;
            DEBUG(4, " NEW PARENT: %s.\n", prev->name);
          }
        } else {
          DEBUG(0, "%s DT_NEEDED %s not found, trying to load\n",
                si->name, need_name);
          if (NULL == load_library(need_name, si->depth + 1)) {
            DL_ERR("Could not load library %s needed by %s.\n",
                   si->name, need_name);
            soinfo_free(si);
            return NULL;
          }
        }
      }
    }

    return si;
}

soinfo* load_library(const char* name, int depth)
{
  void* phdr_mmap = 0;
  Elf32_Addr phdr_size = 0;

  // Open the file.
  DEBUG(2, "Requesting new library %s at priority %d.\n", name, depth);
  int fd = open_library(name);
  if (fd == -1) {
      DL_ERR("Module \"%s\" not found", name);
      return NULL;
  }

  soinfo* info = load_library_fd_phdr(fd, &phdr_mmap, &phdr_size, name, depth);
  close(fd);

  if (phdr_mmap != NULL)
    phdr_table_unload(phdr_mmap, phdr_size);

  if (info != NULL) {
    soinfo_chain(info);
    load_library_process_dynamic(info);
  }
  return info;
}

soinfo *init_library(soinfo *si)
{
    /* At this point we know that whatever is loaded @ base is a valid ELF
     * shared library whose segments are properly mapped in. */
    DEBUG(1, "%s init_library base=0x%08x sz=0x%08x name='%s') ]\n",
          si->name, si->base, si->size);

    if(soinfo_link_image(si)) {
        // NACL MOD BEGIN
        // We do not have the size of data segments so we cannot unmap
        // data segments.
        // TODO(crbug.com/257546): Unmap data segments.
        // NACL MOD END
        munmap((void *)si->base, si->size);
        return NULL;
    }
    return si;
}

soinfo *find_loaded_library(const char *name)
{
    soinfo *si;
    const char *bname;

    // TODO: don't use basename only for determining libraries
    // http://code.google.com/p/android/issues/detail?id=6670

    bname = strrchr(name, '/');
    bname = bname ? bname + 1 : name;

    for(si = solist; si != NULL; si = si->next){
        if(!strcmp(bname, si->name)) {
            return si;
        }
    }
    return NULL;
}

soinfo *find_library(const char *name, int depth)
{
    soinfo* si = find_loaded_library(name);
    if (si != NULL) {
        if(si->flags & FLAG_ERROR) {
            DL_ERR("\"%s\" failed to load previously", name);
            return NULL;
        }
        if(si->flags & FLAG_LINKED) return si;
        DL_ERR("OOPS: recursive link to \"%s\"", si->name);
        return si;
    }

    DEBUG(3, "%s has not been loaded yet.  Locating...\n", name);
    si = load_library(name, depth);
    if(si == NULL)
        return NULL;
    return init_library(si);
}

static void call_destructors(soinfo *si);

int soinfo_unload(soinfo* si) {
    if (si->refcount == 1) {
        DEBUG(1, "%s unloading.\n", si->name);
        call_destructors(si);

        // NACL MOD BEGIN
        // dynamic changed to Elf32_Addr
        for (Elf32_Addr* d = si->dynamic; *d; d += 2) {
        // NACL MOD END
            if(d[0] == DT_NEEDED){
                soinfo *lsi = find_loaded_library(si->strtab + d[1]);
                if (lsi) {
                    DEBUG(2, "%s needs to unload %s\n", si->name, lsi->name);
                    soinfo_unload(lsi);
                } else {
                    // TODO: should we return -1 in this case?
                    DL_ERR("\"%s\": could not unload dependent library",
                           si->name);
                }
            }
        }

        // NACL MOD BEGIN
        // We do not have the size of data segments so we cannot unmap
        // data segments.
        // TODO(crbug.com/257546): Unmap data segments.
        // NACL MOD END
        munmap((char *)si->base, si->size);
        notify_gdb_of_unload(si);
        soinfo_free(si);
        si->refcount = 0;
    } else {
        si->refcount--;
        // NACL MOD BEGIN
        // Replace PRINT with TRACE. The upstream Bionic also changed this.
        DEBUG(1, "Not unloading '%s', decrementing refcount to %d\n",
              si->name, si->refcount);
        // NACL MOD END
    }
    return 0;
}

/* TODO: don't use unsigned for addrs below. It works, but is not
 * ideal. They should probably be either uint32_t, Elf32_Addr, or unsigned
 * long.
 */
// NACL MOD BEGIN
// System V Application Binary Interface AMD64 Architecture
// Processor Supplement says "The AMD64 ABI architectures uses
// only Elf64_Rela relocation entries with explicit addends."
// http://www.x86-64.org/documentation/abi.pdf
#if defined(ANDROID_X86_64_LINKER)
static int soinfo_relocate(soinfo *si, Elf64_Rela *rel, unsigned count,
                           soinfo *needed[])
#else
static int soinfo_relocate(soinfo *si, Elf32_Rel *rel, unsigned count,
                           soinfo *needed[])
#endif
// NACL MOD END
{
    Elf32_Sym *symtab = si->symtab;
    const char *strtab = si->strtab;
    Elf32_Sym *s;
    // NACL MOD BEGIN
    // Initialize |offset| with 0 to suppress gcc-4.8 warning.
    Elf32_Addr offset = 0;
    // AMD64 ABI says we should always use Elf64_Rela for x86-64.
#if defined(ANDROID_X86_64_LINKER)
    Elf64_Rela *start = rel;
#else
    Elf32_Rel *start = rel;
#endif
    // NACL MOD END

    for (size_t idx = 0; idx < count; ++idx, ++rel) {
        // NACL MOD BEGIN
        // Use ELFW(R_*) instead of ELF32_R_*.
        unsigned type = ELFW(R_TYPE)(rel->r_info);
        unsigned sym = ELFW(R_SYM)(rel->r_info);
        // NACL MOD END
        unsigned reloc = (unsigned)(rel->r_offset + si->load_bias);
        unsigned sym_addr = 0;
        char *sym_name = NULL;

//        DEBUG("%5d Processing '%s' relocation at index %d\n", pid,
//              si->name, idx);
        if (type == 0) { // R_*_NONE
            continue;
        }
        if(sym != 0) {
#if !defined(ANDROID_ARM_LINKER)
            bool ignore_local = false;
#else
            bool ignore_local = ((type == R_ARM_COPY) ||
                ((type == R_ARM_GLOB_DAT) && (si->flags & FLAG_EXE)));
#endif
            sym_name = (char *)(strtab + symtab[sym].st_name);
//            DEBUG("  SYMBOL: %s\n", sym_name);
            // NACL MOD BEGIN
            // We must not look up local symbols. RESOLVE_MAP in
            // nacl-glibc/elf/dl-reloc.c handles local symbols similarly.
            //
            // We also modified code in else clause for NaCl. See the
            // comment in the else clause for detail.
            if(ELFW(ST_BIND)(symtab[sym].st_info) == STB_LOCAL) {
                s = &symtab[sym];
                offset = si->load_bias;
            } else {
                // NaCl expects RTLD_GLOBAL semantics. In other words,
                // all symbols should be available for binaries
                // subsequently loaded. To achieve this, we lookup all
                // symbols from all loaded binaries.
                // This needs to be more complex...
                // In the case of R_ARM_GLOB_DAT, first check main, then local
                // In the case of R_ARM_COPY, ignore local
                s = soinfo_do_lookup(si, sym_name, &offset, ignore_local);
            }
            // NACL MOD END
            if(s == NULL) {
                /* We only allow an undefined symbol if this is a weak
                   reference..   */
                s = &symtab[sym];
                // NACL MOD BEGIN
                // Use ELFW(ST_BIND) instead of ELF32_ST_BIND.
                if (ELFW(ST_BIND)(s->st_info) != STB_WEAK) {
                // NACL MOD END
                    DL_ERR("cannot locate symbol \"%s\" referenced by \"%s\"...", sym_name, si->name);
                    debug_verbosity = 9;
                    s = soinfo_do_lookup(si, sym_name, &offset, ignore_local);
                    exit(1);
                    return -1;
                }

                /* IHI0044C AAELF 4.5.1.1:

                   Libraries are not searched to resolve weak references.
                   It is not an error for a weak reference to remain
                   unsatisfied.

                   During linking, the value of an undefined weak reference is:
                   - Zero if the relocation type is absolute
                   - The address of the place if the relocation is pc-relative
                   - The address of nominal base address if the relocation
                     type is base-relative.
                  */

                switch (type) {
#if defined(ANDROID_ARM_LINKER)
                case R_ARM_JUMP_SLOT:
                case R_ARM_GLOB_DAT:
                case R_ARM_ABS32:
                case R_ARM_RELATIVE:    /* Don't care. */
#elif defined(ANDROID_X86_LINKER)
                case R_386_JMP_SLOT:
                case R_386_GLOB_DAT:
                case R_386_32:
                case R_386_RELATIVE:    /* Dont' care. */
                // NACL MOD BEGIN
                // Add cases for x86-64.
#elif defined(ANDROID_X86_64_LINKER)
                case R_X86_64_JMP_SLOT:
                case R_X86_64_GLOB_DAT:
                case R_X86_64_32:
                case R_X86_64_64:
                case R_X86_64_RELATIVE:    /* Don't care. */
                // NACL MOD END
#endif /* ANDROID_*_LINKER */
                    /* sym_addr was initialized to be zero above or relocation
                       code below does not care about value of sym_addr.
                       No need to do anything.  */
                    break;

#if defined(ANDROID_X86_LINKER)
                case R_386_PC32:
                    sym_addr = reloc;
                    break;
#endif /* ANDROID_X86_LINKER */

                // NACL MOD BEGIN
                // Add a case for x86-64.
#if defined(ANDROID_X86_64_LINKER)
                case R_X86_64_PC32:
                    sym_addr = reloc;
                    break;
#endif /* ANDROID_X86_64_LINKER */
                // NACL MOD END
#if defined(ANDROID_ARM_LINKER)
                case R_ARM_COPY:
                    /* Fall through.  Can't really copy if weak symbol is
                       not found in run-time.  */
#endif /* ANDROID_ARM_LINKER */
                default:
                    DL_ERR("unknown weak reloc type %d @ %p (%d)",
                                 type, rel, (int) (rel - start));
                    return -1;
                }
            } else {
                /* We got a definition.  */
#if 0
                if((base == 0) && (si->base != 0)){
                        /* linking from libraries to main image is bad */
                    DL_ERR("cannot locate \"%s\"...",
                           strtab + symtab[sym].st_name);
                    return -1;
                }
#endif
                sym_addr = (unsigned)(s->st_value + offset);
            }
            count_relocation(kRelocSymbol);
        } else {
            s = NULL;
        }
        // NACL MOD BEGIN
        // In x86-64, rel is Elf64_Rela and we use r_addend field.
#if defined(ANDROID_X86_64_LINKER)
        sym_addr += rel->r_addend;
#endif
        // NACL MOD END

/* TODO: This is ugly. Split up the relocations by arch into
 * different files.
 */
        switch(type){
#if defined(ANDROID_ARM_LINKER)
        case R_ARM_JUMP_SLOT:
            count_relocation(kRelocAbsolute);
            MARK(rel->r_offset);
            DEBUG(4, "RELO JMP_SLOT %08x <- %08x %s\n",
                  reloc, sym_addr, sym_name);
            *((unsigned*)reloc) = sym_addr;
            break;
        case R_ARM_GLOB_DAT:
            count_relocation(kRelocAbsolute);
            MARK(rel->r_offset);
            DEBUG(4, "RELO GLOB_DAT %08x <- %08x %s size %d\n",
                  reloc, sym_addr, sym_name, s->st_size);
            *((unsigned*)reloc) = sym_addr;
            break;
        case R_ARM_ABS32:
            count_relocation(kRelocAbsolute);
            MARK(rel->r_offset);
            DEBUG(4, "RELO ABS %08x <- %08x %s\n", reloc, sym_addr, sym_name);
            *((unsigned*)reloc) += sym_addr;
            break;
        case R_ARM_REL32:
            count_relocation(kRelocRelative);
            MARK(rel->r_offset);
            DEBUG(4, "RELO REL32 %08x <- %08x - %08x %s\n",
                  reloc, sym_addr, rel->r_offset, sym_name);
            *((unsigned*)reloc) += sym_addr - rel->r_offset;
            break;
#elif defined(ANDROID_X86_LINKER)
        case R_386_JMP_SLOT:
            count_relocation(kRelocAbsolute);
            MARK(rel->r_offset);
            DEBUG(4, "RELO JMP_SLOT %08x <- %08x %s\n",
                  reloc, sym_addr, sym_name);
            *((unsigned*)reloc) = sym_addr;
            break;
        case R_386_GLOB_DAT:
            count_relocation(kRelocAbsolute);
            MARK(rel->r_offset);
            DEBUG(4, "RELO GLOB_DAT %08x <- %08x %s\n",
                  reloc, sym_addr, sym_name);
            *((unsigned*)reloc) = sym_addr;
            break;
        // NACL MOD BEGIN
        // Add cases for x86-64. Their implementations are almost the
        // same as the cases for x86.
#elif defined(ANDROID_X86_64_LINKER)
        case R_X86_64_JMP_SLOT:
            count_relocation(kRelocAbsolute);
            MARK(rel->r_offset);
            DEBUG(4, "RELO JMP_SLOT %08x <- %08x %s\n",
                   reloc, sym_addr, sym_name);
            *((unsigned*)reloc) = sym_addr;
            break;
        case R_X86_64_GLOB_DAT:
            count_relocation(kRelocAbsolute);
            MARK(rel->r_offset);
            DEBUG(4, "RELO GLOB_DAT %08x <- %08x %s\n",
                  reloc, sym_addr, sym_name);
            *((unsigned*)reloc) = sym_addr;
            break;
        // NACL MOD END
#elif defined(ANDROID_MIPS_LINKER)
    case R_MIPS_JUMP_SLOT:
            count_relocation(kRelocAbsolute);
            MARK(rel->r_offset);
            DEBUG(4, "RELO JMP_SLOT %08x <- %08x %s\n",
                  reloc, sym_addr, sym_name);
            *((unsigned*)reloc) = sym_addr;
            break;
    case R_MIPS_REL32:
            count_relocation(kRelocAbsolute);
            MARK(rel->r_offset);
            DEBUG(4, "RELO REL32 %08x <- %08x %s\n", pid,
                  reloc, sym_addr, (sym_name) ? sym_name : "*SECTIONHDR*");
            if (s) {
                *((unsigned*)reloc) += sym_addr;
            } else {
                *((unsigned*)reloc) += si->base;
            }
            break;
#endif /* ANDROID_*_LINKER */

#if defined(ANDROID_ARM_LINKER)
        case R_ARM_RELATIVE:
#elif defined(ANDROID_X86_LINKER)
        case R_386_RELATIVE:
        // NACL MOD BEGIN
        // Add a case for x86-64.
#elif defined(ANDROID_X86_64_LINKER)
        case R_X86_64_RELATIVE:
        // NACL MOD END
#endif /* ANDROID_*_LINKER */
            count_relocation(kRelocRelative);
            MARK(rel->r_offset);
            if (sym) {
                DL_ERR("odd RELATIVE form...");
                return -1;
            }
            DEBUG(4, "RELO RELATIVE %08x <- +%08x\n", reloc, si->base);
            *((unsigned*)reloc) += si->base;
            break;

#if defined(ANDROID_X86_LINKER)
        case R_386_32:
            count_relocation(kRelocRelative);
            MARK(rel->r_offset);

            DEBUG(4, "RELO R_386_32 %08x <- +%08x %s\n", pid,
                       reloc, sym_addr, sym_name);
            *((unsigned *)reloc) += (unsigned)sym_addr;
            break;

        case R_386_PC32:
            count_relocation(kRelocRelative);
            MARK(rel->r_offset);
            DEBUG(4, "RELO R_386_PC32 %08x <- +%08x (%08x - %08x) %s\n",
                  reloc,(sym_addr - reloc), sym_addr, reloc, sym_name);
            *((unsigned *)reloc) += (unsigned)(sym_addr - reloc);
            break;
#endif /* ANDROID_X86_LINKER */

        // NACL MOD BEGIN
        // Add cases for x86-64. Their implementations are almost the
        // same as the cases for x86.
#if defined(ANDROID_X86_64_LINKER)
        case R_X86_64_32:
            count_relocation(kRelocRelative);
            MARK(rel->r_offset);

            DEBUG(4, "RELO R_X86_64_32 %08x <- +%08x %s\n",
                  reloc, sym_addr, sym_name);
            *((unsigned *)reloc) += (unsigned)sym_addr;
            break;

        case R_X86_64_PC32:
            count_relocation(kRelocRelative);
            MARK(rel->r_offset);
            DEBUG(4, "RELO R_X86_64_PC32 %08x <- +%08x (%08x - %08x) %s\n",
                  reloc, (sym_addr - reloc), sym_addr, reloc, sym_name);
            *((unsigned *)reloc) += (unsigned)(sym_addr - reloc);
            break;
#endif /* ANDROID_X86_64_LINKER */
        // NACL MOD END
#ifdef ANDROID_ARM_LINKER
        case R_ARM_COPY:
            if ((si->flags & FLAG_EXE) == 0) {
                /*
                 * http://infocenter.arm.com/help/topic/com.arm.doc.ihi0044d/IHI0044D_aaelf.pdf
                 *
                 * Section 4.7.1.10 "Dynamic relocations"
                 * R_ARM_COPY may only appear in executable objects where e_type is
                 * set to ET_EXEC.
                 *
                 * TODO: FLAG_EXE is set for both ET_DYN and ET_EXEC executables.
                 * We should explicitly disallow ET_DYN executables from having
                 * R_ARM_COPY relocations.
                 */
                DL_ERR("%s R_ARM_COPY relocations only supported for ET_EXEC", si->name);
                return -1;
            }
            count_relocation(kRelocCopy);
            MARK(rel->r_offset);
            DEBUG(4, "RELO %08x <- %d @ %08x %s size %d.\n",
                  reloc, s->st_size, sym_addr, sym_name, s->st_size);
            if (reloc == sym_addr) {
                DL_ERR("%5d RELO %08x <- %d @ %08x %s %s\n", pid,
                       reloc, s->st_size, sym_addr, sym_name, si->name);
                DL_ERR("Internal linker error detected. reloc == symaddr");
                return -1;
            }
            memcpy((void*)reloc, (void*)sym_addr, s->st_size);
            break;
#endif /* ANDROID_ARM_LINKER */

        default:
            DL_ERR("unknown reloc type %d @ %p (%d) for %s in %s",
                   type, rel, (int) (rel - start), sym_name, si->name);
            return -1;
        }
    }
    return 0;
}

#ifdef ANDROID_MIPS_LINKER
static int mips_relocate_got(soinfo* si, soinfo* needed[]) {
    unsigned *got;
    unsigned local_gotno, gotsym, symtabno;
    Elf32_Sym *symtab, *sym;
    unsigned g;

    got = si->plt_got;
    local_gotno = si->mips_local_gotno;
    gotsym = si->mips_gotsym;
    symtabno = si->mips_symtabno;
    symtab = si->symtab;

    /*
     * got[0] is address of lazy resolver function
     * got[1] may be used for a GNU extension
     * set it to a recognizable address in case someone calls it
     * (should be _rtld_bind_start)
     * FIXME: maybe this should be in a separate routine
     */

    if ((si->flags & FLAG_LINKER) == 0) {
        g = 0;
        got[g++] = 0xdeadbeef;
        if (got[g] & 0x80000000) {
            got[g++] = 0xdeadfeed;
        }
        /*
         * Relocate the local GOT entries need to be relocated
         */
        for (; g < local_gotno; g++) {
            got[g] += si->load_bias;
        }
    }

    /* Now for the global GOT entries */
    sym = symtab + gotsym;
    got = si->plt_got + local_gotno;
    for (g = gotsym; g < symtabno; g++, sym++, got++) {
        const char *sym_name;
        unsigned base;
        Elf32_Sym *s;

        /* This is an undefined reference... try to locate it */
        sym_name = si->strtab + sym->st_name;
        s = soinfo_do_lookup(si, sym_name, &base, needed, false);
        if (s == NULL) {
            /* We only allow an undefined symbol if this is a weak
               reference..   */
            s = &symtab[g];
            // NACL MOD BEGIN
            // Use ELFW(ST_BIND) instead of ELF32_ST_BIND.
            if (ELFW(ST_BIND)(s->st_info) != STB_WEAK) {
            // NACL MOD END
                DL_ERR("cannot locate \"%s\"...", sym_name);
                return -1;
            }
            *got = 0;
        }
        else {
            /* FIXME: is this sufficient?
             * For reference see NetBSD link loader
             * http://cvsweb.netbsd.org/bsdweb.cgi/src/libexec/ld.elf_so/arch/mips/mips_reloc.c?rev=1.53&content-type=text/x-cvsweb-markup
             */
             *got = base + s->st_value;
        }
    }
    return 0;
}
#endif

/* Please read the "Initialization and Termination functions" functions.
 * of the linker design note in bionic/linker/README.TXT to understand
 * what the following code is doing.
 *
 * The important things to remember are:
 *
 *   DT_PREINIT_ARRAY must be called first for executables, and should
 *   not appear in shared libraries.
 *
 *   DT_INIT should be called before DT_INIT_ARRAY if both are present
 *
 *   DT_FINI should be called after DT_FINI_ARRAY if both are present
 *
 *   DT_FINI_ARRAY must be parsed in reverse order.
 */

static void call_array(unsigned *ctor, int count, int reverse)
{
    int n, inc = 1;

    if (reverse) {
        ctor += (count-1);
        inc   = -1;
    }

    for(n = count; n > 0; n--) {
        void (*func)() = (void (*)()) *ctor;
        ctor += inc;
        if(((int) func == 0) || ((int) func == -1)) continue;
        DEBUG(3, "  Calling func @ 0x%08x\n", (unsigned)func);
        func();
    }
}

static void soinfo_call_preinit_constructors(soinfo *si)
{
  if (si->preinit_array_count == 0) {
    DEBUG(2, "Skipping preinit_array @ 0x%08x [%d] for '%s' ]\n",
        (unsigned)si->preinit_array, si->preinit_array_count,
        si->name);
    return;
  }
  DEBUG(2, "Calling preinit_array @ 0x%08x [%d] for '%s' ]\n",
       (unsigned)si->preinit_array, si->preinit_array_count,
       si->name);
  call_array(si->preinit_array, si->preinit_array_count, 0);
  DEBUG(2, "Done calling preinit_array for '%s'\n", si->name);
}

void soinfo_call_constructors(soinfo *si)
{
    if (si->constructors_called) {
        DEBUG(2, "Already called on %s.\n", si->name);
        return;
    }

    // Set this before actually calling the constructors, otherwise it doesn't
    // protect against recursive constructor calls. One simple example of
    // constructor recursion is the libc debug malloc, which is implemented in
    // libc_malloc_debug_leak.so:
    // 1. The program depends on libc, so libc's constructor is called here.
    // 2. The libc constructor calls dlopen() to load libc_malloc_debug_leak.so.
    // 3. dlopen() calls soinfo_call_constructors() with the newly created
    //    soinfo for libc_malloc_debug_leak.so.
    // 4. The debug so depends on libc, so soinfo_call_constructors() is
    //    called again with the libc soinfo. If it doesn't trigger the early-
    //    out above, the libc constructor will be called again (recursively!).
    si->constructors_called = 1;

    // NACL MOD BEGIN
    // Print the elapsed time for calling init functions.
    DEBUG(2, "Calling constructors for %s.\n", si->name);
    // NACL MOD END
    if (!(si->flags & FLAG_EXE) && si->preinit_array) {
      DL_ERR("shared library \"%s\" has a preinit_array table @ 0x%08x. "
          "This is INVALID.", si->name, (unsigned) si->preinit_array);
    }

    if (si->dynamic) {
        // NACL MOD BEGIN
        // dynamic changed to Elf32_Addr
        Elf32_Addr *d;
        // NACL MOD END
        for(d = si->dynamic; *d; d += 2) {
            if(d[0] == DT_NEEDED){
                DEBUG(2, "NEEDED %s.\n", si->strtab + d[1]);
                soinfo* lsi = find_loaded_library(si->strtab + d[1]);
                if (!lsi) {
                    DL_ERR("\"%s\": could not initialize dependent library %s",
                           si->name, si->strtab + d[1]);
                } else {
                    soinfo_call_constructors(lsi);
                    DEBUG(4, "Returning to %s.\n", si->name);
                }
                DEBUG(4, "End of needed for %s.\n", si->name);
            }
        }
    }

    if (si->init_func) {
        DEBUG(3, "Calling init_func @ 0x%08x for '%s'.\n",
              (unsigned)si->init_func, si->name);
        si->init_func();
        DEBUG(3, "Done calling init_func for '%s'.\n", si->name);
    }

    if (si->init_array) {
        DEBUG(3, "Calling init_array @ 0x%08x [%d] for '%s'.\n",
              (unsigned)si->init_array, si->init_array_count, si->name);
        call_array(si->init_array, si->init_array_count, 0);
        DEBUG(3, "Done calling init_array for '%s'.\n", si->name);
    }
    DEBUG(2, "Constructors done for %s.\n", si->name);
}

static void call_destructors(soinfo *si)
{
    if (si->fini_array) {
        DEBUG(3, "Calling fini_array @ 0x%08x [%d] for '%s'.\n",
              (unsigned)si->fini_array, si->fini_array_count, si->name);
        call_array(si->fini_array, si->fini_array_count, 1);
        DEBUG(3, "Done calling fini_array for '%s'.\n", si->name);
    }

    if (si->fini_func) {
        DEBUG(3, "Calling fini_func @ 0x%08x for '%s' ]\n",
              (unsigned)si->fini_func, si->name);
        si->fini_func();
        DEBUG(3, "Done calling fini_func for '%s' ]\n", si->name);
    }
}

int soinfo_link_image(soinfo *si)
{
    // NACL MOD BEGIN
    // dynamic changed to Elf32_Addr
    Elf32_Addr *d;
    // NACL MOD END
    /* "base" might wrap around UINT32_MAX. */
    Elf32_Addr base = si->load_bias;
    const Elf32_Phdr *phdr = si->phdr;
    int phnum = si->phnum;
    int relocating_linker = (si->flags & FLAG_LINKER) != 0;
    soinfo **needed, **pneeded;
    size_t dynamic_count;
    // NACL MOD BEGIN
    // Define rel_size.

    if (si->next)
      soinfo_link_image(si->next);

#if defined(ANDROID_X86_64_LINKER)
    static const size_t rel_size = sizeof(Elf64_Rela);
#else
//    static const size_t rel_size = sizeof(Elf32_Rel);
#endif
    // NACL MOD END

    /* We can't debug anything until the linker is relocated */
    if (!relocating_linker) {
        DEBUG(1, "%s si->base = 0x%08x si->flags = 0x%08x\n",
            si->name, si->base, si->flags);
    }

    /* Extract dynamic section */
    phdr_table_get_dynamic_section(phdr, phnum, base, &si->dynamic,
                                   &dynamic_count);
    if (si->dynamic == NULL) {
        if (!relocating_linker) {
            DL_ERR("missing PT_DYNAMIC?!");
        }
        goto fail;
    } else {
        if (!relocating_linker) {
            DEBUG(1, "%s dynamic = %p\n", si->name, si->dynamic);
        }
    }
    // NACL MOD BEGIN UPSTREAM
    // We did not initialize value to l_ld in the main binary yet.
    // For other binaries, this field is initialized in
    // insert_soinfo_into_debug_map but the Bionic loader does not
    // call this function for the main binary. This change would be
    // upstreamable and we do not need #ifdef __native_client__
    // because setting appropriate value for this field would be
    // beneficial anyway.
    if (si->flags & FLAG_EXE)
        si->linkmap.l_ld = (uintptr_t)si->dynamic;
    // NACL MOD END UPSTREAM

#ifdef ANDROID_ARM_LINKER
    (void) phdr_table_get_arm_exidx(phdr, phnum, base,
                                    &si->ARM_exidx, &si->ARM_exidx_count);
#endif

    /* extract useful information from dynamic section */
    /* dynamic_count is an upper bound for the number of needed libs */
    pneeded = needed = (soinfo**) alloca((1 + dynamic_count) * sizeof(soinfo*));

    for(d = si->dynamic; *d; d += 2) {
        if(d[0] == DT_NEEDED){
            DEBUG(2, "%s needs %s\n", si->name, si->strtab + d[1]);
            soinfo *lsi = find_loaded_library(si->strtab + d[1]);
            if(lsi == 0) {
                strlcpy(tmp_err_buf, linker_get_error(), sizeof(tmp_err_buf));
                DL_ERR("could not load library \"%s\" needed by \"%s\"; caused by %s",
                       si->strtab + d[1], si->name, tmp_err_buf);
                goto fail;
            }
            *pneeded++ = lsi;
            lsi->refcount++;
        }
    }
    *pneeded = NULL;

    if (si->has_text_relocations) {
        /* Unprotect the segments, i.e. make them writable, to allow
         * text relocations to work properly. We will later call
         * phdr_table_protect_segments() after all of them are applied
         * and all constructors are run.
         */
        if (phdr_table_unprotect_segments(si->phdr, si->phnum, si->load_bias) < 0) {
            DL_ERR("can't unprotect loadable segments for \"%s\": %s",
                   si->name, strerror(errno));
            goto fail;
        }
    }

    if(si->plt_rel) {
        DEBUG(2, "Relocating %s plt.\n", si->name );
        if(soinfo_relocate(si, si->plt_rel, si->plt_rel_count, needed))
            goto fail;
    }
    if(si->rel) {
        DEBUG(2, "Relocating %s.\n", si->name );
        if(soinfo_relocate(si, si->rel, si->rel_count, needed))
            goto fail;
    }

#ifdef ANDROID_MIPS_LINKER
    if(mips_relocate_got(si, needed)) {
        goto fail;
    }
#endif

    si->flags |= FLAG_LINKED;
    DEBUG(1, "Finished linking %s ]\n", si->name);

    if (si->has_text_relocations) {
        /* All relocations are done, we can protect our segments back to
         * read-only. */
        if (phdr_table_protect_segments(si->phdr, si->phnum, si->load_bias) < 0) {
            DL_ERR("can't protect segments for \"%s\": %s",
                   si->name, strerror(errno));
            goto fail;
        }
    }

    /* We can also turn on GNU RELRO protection */
    if (phdr_table_protect_gnu_relro(si->phdr, si->phnum, si->load_bias) < 0) {
        DL_ERR("can't enable GNU RELRO protection for \"%s\": %s",
               si->name, strerror(errno));
        goto fail;
    }

    notify_gdb_of_load(si);
    return 0;

fail:
    ERROR("failed to link %s\n", si->name);
    si->flags |= FLAG_ERROR;
    return -1;
}

/*
 * This code is called after the linker has linked itself and
 * fixed it's own GOT. It is safe to make references to externs
 * and other non-local data at this point.
 */
static unsigned __linker_init_post_relocation(unsigned **elfdata, unsigned linker_base)
{
    // NACL MOD BEGIN
    // NaCl does not use this variable.
#if !defined(__native_client__)
    static soinfo linker_soinfo;
#endif
    // NACL MOD END

    int argc = (int) *elfdata;
    char **argv = (char**) (elfdata + 1);
    unsigned *vecs = (unsigned*) (argv + argc + 1);
    unsigned *v;
    soinfo *si;
    const char *ldpath_env = NULL;

#if !defined(__native_client__)
    const char *ldpreload_env = NULL;
#endif

    /* NOTE: we store the elfdata pointer on a special location
     *       of the temporary TLS area in order to pass it to
     *       the C Library's runtime initializer.
     *
     *       The initializer must clear the slot and reset the TLS
     *       to point to a different location to ensure that no other
     *       shared library constructor can access it.
     */
    __libc_init_tls(elfdata);

    pid = getpid();

#if TIMING
    struct timeval t0, t1;
    gettimeofday(&t0, 0);
#endif

    /* Initialize environment functions, and get to the ELF aux vectors table */
    vecs = linker_env_init(vecs);

    /* Check auxv for AT_SECURE first to see if program is setuid, setgid,
       has file caps, or caused a SELinux/AppArmor domain transition. */
    for (v = vecs; v[0]; v += 2) {
        if (v[0] == AT_SECURE) {
            /* kernel told us whether to enable secure mode */
            program_is_setuid = v[1];
            goto sanitize;
        }
    }

    // NACL MOD BEGIN
    // NaCl does not have setuid, and we always honor LD_LIBRARY_PATH
    // and LD_PRELOAD.
#if !defined(__native_client__)
    /* Kernel did not provide AT_SECURE - fall back on legacy test. */
    program_is_setuid = (getuid() != geteuid()) || (getgid() != getegid());
#endif
    // NACL MOD END

sanitize:
    /* Sanitize environment if we're loading a setuid program */
    if (program_is_setuid) {
        linker_env_secure();
    }

    // NACL MOD BEGIN
    // NaCl does not have signal handlers so there is no reason we
    // need to call debugger_init, which depends on signals.
#if !defined(__native_client__)
    debugger_init();
#endif
    // NACL MOD END

    /* Get a few environment variables */
    {
#if LINKER_DEBUG
        const char* env;
        env = linker_env_get("DEBUG"); /* XXX: TODO: Change to LD_DEBUG */
        if (env)
            debug_verbosity = atoi(env);
#endif

        /* Normally, these are cleaned by linker_env_secure, but the test
         * against program_is_setuid doesn't cost us anything */
        if (!program_is_setuid) {
            ldpath_env = linker_env_get("LD_LIBRARY_PATH");
            // NACL MOD BEGIN
            // When LD_LIBRARY_PATH is not specified, we will use the
            // default library load path. See nacl-glibc/elf/dl-load.c.
#if defined(__native_client__)
            if (!ldpath_env)
                ldpath_env = DL_DST_LIB;
#else
            ldpreload_env = linker_env_get("LD_PRELOAD");
#endif
            // NACL MOD END
        }
    }

    struct soinfo* itr = solist;
    DEBUG(2, "Search Order:\n");
    while (itr) {
      DEBUG(2, "  %s\n", itr->name);
      itr = itr->next;
    }

    DEBUG(1, "Elfdata @ 0x%08x\n", (unsigned)elfdata);

    // NACL MOD BEGIN
    // As sel_ldr does not load the main program, we loaded the main
    // binary by ourselves in __nacl_linker_init. We should just reuse
    // it not to create an unnecessary element in the link list.
#if defined(__native_client__)
    si = solist->next;
#else
    si = soinfo_alloc(argv[0]);
#endif
    // NACL MOD END
    if(si == 0) {
        exit(-1);
    }

    /* bootstrap the link map, the main exe always needs to be first */
    // si->flags |= FLAG_EXE;
    // link_map* map = &(si->linkmap);

    // map->l_addr = 0;
    // map->l_name = argv[0];
    // map->l_prev = NULL;
    // map->l_next = NULL;

    // _r_debug.r_map = map;
    // r_debug_tail = map;

    // NACL MOD BEGIN
    // We disable debug info related stuff. On NaCl, gdb will interact
    // with the loader in the host so we need to do nothing for it.
#if !defined(__native_client__)
    // NACL MOD END
        /* gdb expects the linker to be in the debug shared object list.
         * Without this, gdb has trouble locating the linker's ".text"
         * and ".plt" sections. Gdb could also potentially use this to
         * relocate the offset of our exported 'rtld_db_dlactivity' symbol.
         * Don't use soinfo_alloc(), because the linker shouldn't
         * be on the soinfo list.
         */
    strlcpy((char*) linker_soinfo.name, "/system/bin/linker", sizeof linker_soinfo.name);
    linker_soinfo.flags = 0;
    linker_soinfo.base = linker_base;
    /*
     * Set the dynamic field in the link map otherwise gdb will complain with
     * the following:
     *   warning: .dynamic section for "/system/bin/linker" is not at the
     *   expected address (wrong library or version mismatch?)
     */
    Elf32_Ehdr *elf_hdr = (Elf32_Ehdr *) linker_base;
    Elf32_Phdr *phdr =
        (Elf32_Phdr *)((unsigned char *) linker_base + elf_hdr->e_phoff);
    phdr_table_get_dynamic_section(phdr, elf_hdr->e_phnum, linker_base,
                                   &linker_soinfo.dynamic, NULL);
    insert_soinfo_into_debug_map(&linker_soinfo);

    // NACL MOD BEGIN
    // Note that we are in #if !defined(__native_client__) so this
    // code will not be used.
    //
    // We already initialized them in load_library.
    // NACL MOD END
    /* extract information passed from the kernel */
    while(vecs[0] != 0){
        switch(vecs[0]){
        case AT_PHDR:
            si->phdr = (Elf32_Phdr*) vecs[1];
            break;
        case AT_PHNUM:
            si->phnum = (int) vecs[1];
            break;
        case AT_ENTRY:
            si->entry = vecs[1];
            break;
        }
        vecs += 2;
    }

    // NACL MOD BEGIN
    // Note that we are in #if !defined(__native_client__) so this
    // code will not be used.
    //
    // On NaCl, we load the main executable in __nacl_linker_init
    // using load_library and |si| is already initialized in
    // load_library. So, we do not need to update these fields.
    // Also, arm-nacl-gcc maps PT_PHDR at the beginning of the data
    // segment, so this check is wrong.
    // NACL MOD END
    /* Compute the value of si->base. We can't rely on the fact that
     * the first entry is the PHDR because this will not be true
     * for certain executables (e.g. some in the NDK unit test suite)
     */
    int nn;
    si->base = 0;
    si->size = phdr_table_get_load_size(si->phdr, si->phnum);
    si->load_bias = 0;
    for ( nn = 0; nn < si->phnum; nn++ ) {
        if (si->phdr[nn].p_type == PT_PHDR) {
            si->load_bias = (Elf32_Addr)si->phdr - si->phdr[nn].p_vaddr;
            si->base = (Elf32_Addr) si->phdr - si->phdr[nn].p_offset;
            break;
        }
    }
    // NACL MOD BEGIN
    // dynamic changed to Elf32_Addr
    si->dynamic = (Elf32_Addr *)-1;
#endif  // !__native_client__
    // NACL MOD END
    si->refcount = 1;

    if (soinfo_link_image(si)) {
      char errmsg[] = "\nCANNOT LINK EXECUTABLE\n";
      write(2, __linker_dl_err_buf, strlen(__linker_dl_err_buf));
      write(2, errmsg, sizeof(errmsg));
      exit(-1);
    }

    soinfo_call_preinit_constructors(si);
    soinfo_call_constructors(si);
    DEBUG(0,"Ready to execute '%s' @ 0x%08x ]\n", si->name, si->entry);
    return si->entry;
}

/*
 * Find the value of AT_BASE passed to us by the kernel. This is the load
 * location of the linker.
 */
static unsigned find_linker_base(unsigned **elfdata) {
    int argc = (int) *elfdata;
    char **argv = (char**) (elfdata + 1);
    unsigned *vecs = (unsigned*) (argv + argc + 1);
    while (vecs[0] != 0) {
        vecs++;
    }

    /* The end of the environment block is marked by two NULL pointers */
    vecs++;

    while(vecs[0]) {
        if (vecs[0] == AT_BASE) {
            return vecs[1];
        }
        vecs += 2;
    }

    return 0; // should never happen
}

// NACL MOD BEGIN
// This is only used for the relocation of the loader and NaCl do not
// relocate the loader for now.
#if !defined(__native_client__)
// NACL MOD END
/* Compute the load-bias of an existing executable. This shall only
 * be used to compute the load bias of an executable or shared library
 * that was loaded by the kernel itself.
 *
 * Input:
 *    elf    -> address of ELF header, assumed to be at the start of the file.
 * Return:
 *    load bias, i.e. add the value of any p_vaddr in the file to get
 *    the corresponding address in memory.
 */
static Elf32_Addr
get_elf_exec_load_bias(const Elf32_Ehdr* elf)
{
    Elf32_Addr        offset     = elf->e_phoff;
    const Elf32_Phdr* phdr_table = (const Elf32_Phdr*)((char*)elf + offset);
    const Elf32_Phdr* phdr_end   = phdr_table + elf->e_phnum;
    const Elf32_Phdr* phdr;

    for (phdr = phdr_table; phdr < phdr_end; phdr++) {
        if (phdr->p_type == PT_LOAD) {
            return (Elf32_Addr)elf + phdr->p_offset - phdr->p_vaddr;
        }
    }
    return 0;
}

// NACL MOD BEGIN
// This is only used for the relocation of the loader and NaCl do not
// relocate the loader for now.
#endif  // !__native_client__
// NACL MOD END
/*
 * This is the entry point for the linker, called from begin.S. This
 * method is responsible for fixing the linker's own relocations, and
 * then calling __linker_init_post_relocation().
 *
 * Because this method is called before the linker has fixed it's own
 * relocations, any attempt to reference an extern variable, extern
 * function, or other GOT reference will generate a segfault.
 */
EXTERN_C unsigned __linker_init(unsigned **elfdata) {
    unsigned linker_addr = find_linker_base(elfdata);
    // NACL MOD BEGIN
    // On real Android, the Bionic loader is a shared object and it
    // has a few relocation entries whose type is R_*_RELATIVE maybe
    // for address randomization. For NaCl, we use statically linked
    // binary as the loader so we do not need to relocate the loader.
#if !defined(__native_client__)
    // NACL MOD END
    Elf32_Ehdr *elf_hdr = (Elf32_Ehdr *) linker_addr;
    Elf32_Phdr *phdr =
        (Elf32_Phdr *)((unsigned char *) linker_addr + elf_hdr->e_phoff);

    soinfo linker_so;
    memset(&linker_so, 0, sizeof(soinfo));

    linker_so.base = linker_addr;
    linker_so.size = phdr_table_get_load_size(phdr, elf_hdr->e_phnum);
    linker_so.load_bias = get_elf_exec_load_bias(elf_hdr);
    linker_so.dynamic = (unsigned *) -1;
    linker_so.phdr = phdr;
    linker_so.phnum = elf_hdr->e_phnum;
    linker_so.flags |= FLAG_LINKER;

    if (soinfo_link_image(&linker_so)) {
        // It would be nice to print an error message, but if the linker
        // can't link itself, there's no guarantee that we'll be able to
        // call write() (because it involves a GOT reference).
        //
        // This situation should never occur unless the linker itself
        // is corrupt.
        exit(-1);
    }
    // NACL MOD BEGIN
    // Bionic's loader does not have relocation info on NaCl.
#endif
    // NACL MOD END

    // We have successfully fixed our own relocations. It's safe to run
    // the main part of the linker now.
    return __linker_init_post_relocation(elfdata, linker_addr);
}
// NACL MOD BEGIN
// The entry point
#if defined(__native_client__)

EXTERN_C unsigned __nacl_linker_args(int envc, char** envp, int argc,
                                       char** argv) {

  // Start with 1 so we ignore the name of the loader
  int args_used = 1;

  ldpaths[0] = NULL;
  while (args_used < argc && argv[args_used][0] == '-') {
    if (!strcmp("--library-path", argv[args_used])) {
      strncpy(ldpaths_buf, argv[args_used + 1], LDPATH_BUFSIZE);

      char *ptr = ldpaths_buf;
      int path_cnt = 0;

      while (ptr && path_cnt < LDPATH_MAX) {
        ldpaths[path_cnt++] = ptr;
        while(*ptr && *ptr != ':')
          ptr++;
        if (*ptr) {
          *ptr = 0;
          ptr++;
        }
      }

      args_used += 2;
      continue;
    }
    if (!strcmp("-v", argv[args_used])) {
      args_used++;
      debug_verbosity++;
      continue;
    }

    DL_ERR("Unknown loader switch: %s\n", argv[0]);
    exit(-1);
  }

  return args_used;
}

EXTERN_C soinfo libdl_info;

EXTERN_C unsigned __nacl_linker_init(unsigned **elfdata) {
    int envc = (int)elfdata[1];
    int argc = (int)elfdata[2];
    char **argv = (char**)&elfdata[3];
    char **envp = argv + argc + 1;
    unsigned **auxv = (unsigned **)(envp + envc + 1);
    int i;

    if (argc < 1) {
        DL_ERR("no file\n");
        exit(-1);
    }

    somain = load_library(argv[0], 0);
    if (NULL == somain) {
      DL_ERR("Failed to find main executable.\n");
      exit(1);
    }

    static const unsigned kLinkerBaseAddress = 0x20000;
    // auxv[0] and auxv[1] was filled by _start for AT_SYSINFO and we
    // must not update it. See bionic/linker/arch/nacl/begin.c for detail.
    if (auxv[0] == AT_NULL || auxv[1] == NULL) {
        DL_ERR("auxv[0] or auxv[1] are not filled.\n");
        exit(-1);
    }
    if (auxv[2] != AT_NULL || auxv[3] != NULL) {
        DL_ERR("auxv[2] or auxv[3] are already filled.\n");
        exit(-1);
    }
    i = 2;
    auxv[i++] = (unsigned *)AT_BASE;
    auxv[i++] = (unsigned *)kLinkerBaseAddress;
    auxv[i++] = (unsigned *)AT_PHDR;
    auxv[i++] = (unsigned *)somain->phdr;
    auxv[i++] = (unsigned *)AT_PHNUM;
    auxv[i++] = (unsigned *)somain->phnum;
    auxv[i++] = (unsigned *)AT_ENTRY;
    auxv[i++] = (unsigned *)somain->entry;
    auxv[i++] = (unsigned *)AT_NULL;
    auxv[i++] = NULL;

    // __linker_init does not use the first two elements.
    return __linker_init(&elfdata[2]);
}

#endif
// NACL MOD END
